//
//  MSHomeViewController.m
//  SocietySale
//
//  Created by Mike on 16/10/25.
//  Copyright © 2016年 Mike. All rights reserved.
//

#define BtnWidth           (SCREEN_WIDTH/2)
#define BackViewHeight     (SCREEN_HEIGHT-KNavBarHeight-KTabBarHeight-160)

#import "MSHomeViewController.h"
#import "MSHomeTableViewController.h"
#import "MSSearchViewController.h"
#import "MSPreferenceSetViewController.h"
#import "MSProjectDetailViewController.h"
#import "MSCustomerRecommenVC.h"
#import "MSCustomerMatchingVC.h"
#import "MSMemberServeViewController.h"

#import "TestViewController.h"
@interface MSHomeViewController ()
{
    BOOL isSelectArea;
    BOOL isSelectIndustry;
    BOOL isSelectStage;
    NSString *documentsPath;
    NSFileManager* fileManager;
    NSString *currentProviceStr;
    NSString *currentCityStr;
    NSString *currentIndustryStr;
    NSString *currentStateStr;
    NSString *currentInvetStr;
    NSString *currentTimeStr;
}
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, assign) float positionY;
//侧边view
@property (nonatomic, strong) UIImageView *sideView;
@property (nonatomic, strong) GXButton            *trackBtn;
@property (nonatomic, strong) GXButton            *attentionBtn;
@property (nonatomic, strong) GXButton            *recommendBtn;
@property (nonatomic, strong) GXButton            *searchBtn;
@property (nonatomic, strong) HDImageMenuView     *menu;
@property (nonatomic, strong) MSDoubleListFilterVC              *areaFilterVC;       //地区筛选
@property (nonatomic, strong) MSSaleFilterViewController        *industryFilterVC;   //行业筛选
@property (nonatomic, strong) MSSaleFilterViewController        *stateFilterVC;      //阶段筛选
@property (nonatomic, strong) MSSaleFilterViewController        *investFilterVC;     //投资筛选
@property (nonatomic, strong) MSSaleFilterViewController        *timeFilterVC;       //时间筛选
@property (nonatomic, strong) MSSaleFilterViewController        *filterVC;           //筛选控件
@property (nonatomic, strong) MSSelectTimeView                  *selectTimeView;     //选择时间
@property (nonatomic, strong) MSHomeTableViewController         *tableVC;
@property (nonatomic, strong) NSMutableArray                    *filterVCArray;
@property (nonatomic, strong) NSMutableArray                    *stateVCArray;
@property (nonatomic, assign) NSInteger lastIndex;
@property (nonatomic, assign) BOOL selectTime;
@property (nonatomic, copy) NSString *areaStr;
@property (nonatomic, copy) NSString *industryStr;
@property (nonatomic, copy) NSString *stateStr;

@end

@implementation MSHomeViewController

- (void)initNavigationBar{
    [super initNavigationBar];
    titleLable.text = @"项目";
//    leftBarBtn.hidden = NO;
    rightBarBtn.hidden = NO;
    
    [leftBarBtn setTitle:@"测试" forState:UIControlStateNormal];
    [leftBarBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [rightBarBtn setImage:[UIImage imageNamed:@"plus"] forState:UIControlStateNormal];
    [rightBarBtn addTarget:self action:@selector(rightBarBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    
    _searchBtn = [GXButton buttonWithType:UIButtonTypeCustom];
    _searchBtn.relayout = YES;
    _searchBtn.imageViewFrame = CGRectMake(10, 12, 21, 20);
    _searchBtn.tag = 40;
    _searchBtn.frame = CGRectMake(SCREENWIDTH-90, 20, 40, 44);
    [_searchBtn setImage:[UIImage imageNamed:@"search_white"] forState:UIControlStateNormal];
    [_searchBtn addTarget:self action:@selector(headBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_navBarView addSubview:_searchBtn];
}

- (void)initUI{
    _positionY = 40;
    NSUserDefaults *defaultes = [NSUserDefaults standardUserDefaults];
    NSString *FirstSET = [defaultes objectForKey:@"FirstSET"];
    if (!FirstSET.length) {
        MSPreferenceSetViewController *vc = [[MSPreferenceSetViewController alloc] init];
        vc.isFirst = YES;
        [rootNavigation pushViewController:vc animated:NO];
        
        [defaultes setObject:@"FirstSET" forKey:@"FirstSET"];
        [defaultes synchronize];
    }
    
    NSArray *titleArr = [NSArray arrayWithObjects:@"地区",@"行业",@"阶段",@"投资",@"时间", nil];
    self.menu = [[HDImageMenuView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40) titleArray:titleArr];
    self.menu.delegate = (id)self;
    self.menu.isHiddenBottomLine = NO;
    [self.contentView addSubview:self.menu];
    
    self.tableVC = [[MSHomeTableViewController alloc] initWithStyle:UITableViewStylePlain];
    self.tableVC.view.frame = CGRectMake(0, 40, SCREEN_WIDTH, SCREEN_HEIGHT-KNavBarHeight-KTabBarHeight-40);
    self.tableVC.enableRefresh = YES;
    self.tableVC.enableRequest = YES;
    self.tableVC.delegate = (id)self;
    self.tableVC.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.contentView addSubview:self.tableVC.view];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss)];
    tapGesture.delegate = (id)self;
    [self.view addGestureRecognizer:tapGesture];
    
    [self layoutHeadView];
    
    _lastIndex = -1;
//    self.areaFilterVC = [[MSDoubleListFilterVC alloc] init];
//    _areaFilterVC.delegate=(id<MSDoubleListFilterVCDelegate>)self;
    self.industryFilterVC = [self creatFilterVC];
    self.stateFilterVC = [self creatFilterVC];
    self.investFilterVC = [self creatFilterVC];
    self.timeFilterVC = [self creatFilterVC];
    
    self.filterVCArray = [NSMutableArray arrayWithObjects:self.areaFilterVC,self.industryFilterVC,self.stateFilterVC,self.investFilterVC,self.timeFilterVC, nil];
    
    _selectTimeView = [[MSSelectTimeView alloc] initWithFrame:CGRectMake(0, 224, SCREEN_WIDTH, SCREEN_HEIGHT-224)];
    _selectTimeView.hidden = YES;
    _selectTimeView.delegate = (id)self;
    UIWindow *window = [UIApplication sharedApplication].windows[0];
    [window addSubview:_selectTimeView];
    
    documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) firstObject];
    fileManager = [NSFileManager defaultManager];
    currentProviceStr = @"";
    currentCityStr = @"";
    currentIndustryStr = @"";
    currentStateStr = @"";
    currentInvetStr = @"";
    currentTimeStr = @"";
    isSelectArea = NO;
    isSelectIndustry = NO;
    isSelectStage = NO;
    
    [self initPreference];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(preferenceAreaChange) name:KPreferenceAreaChange object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(preferenceIndustryChange) name:KPreferenceIndustryChange object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(preferenceStageChange) name:KPreferenceStageChange object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess) name:KLoginSuccess object:nil];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([touch.view.superview isKindOfClass:[UITableViewCell class]]) {
        return NO;
    }
    return YES;
}

- (void)dismiss{
    _sideView.hidden = YES;
    rightBarBtn.selected = NO;
}
- (void)leftBarBtnAction{
    TestViewController *vc = [[TestViewController alloc] init];
    [rootNavigation pushViewController:vc animated:YES];
}

- (void)rightBarBtnAction:(GXButton*)btn{
    btn.selected = !btn.selected;
    if (btn.selected) {
        if (!_sideView) {
            _sideView = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-85, 70, 80, 210)];
            UIImage *newImage = [[UIImage imageNamed:@"pop_bg"] stretchableImageWithLeftCapWidth:0 topCapHeight:35];
            _sideView.image = newImage;
            _sideView.userInteractionEnabled = YES;
            _sideView.clipsToBounds = YES;
            [self.view addSubview:_sideView];
            NSArray *titleArray = @[@"发布交易",@"客户追踪",@"客户引荐",@"会员服务",@"偏好设置"];
            for (int i =0; i<5; i++) {
                GXButton *sideButton = [GXButton buttonWithType:UIButtonTypeCustom];
                [sideButton setFrame:CGRectMake(0, 5+i*40, 80, 40)];
                sideButton.tag = 10+i;
                //                [sideButton setImage:[UIImage imageNamed:titleArray[i]] forState:UIControlStateNormal];
                sideButton.titleLabel.font = HeitiFont(15);
                [sideButton setTitle:titleArray[i] forState:UIControlStateNormal];
                [sideButton setTitleColor:kLightGrayColor forState:UIControlStateHighlighted];
                [sideButton addTarget:self action:@selector(sideButtonAction:) forControlEvents:UIControlEventTouchUpInside];
                [_sideView addSubview:sideButton];
                
//                UIView *sublineView = [[UIView alloc] initWithFrame:CGRectMake(10, sideButton.bottom, 60, 0.5)];
//                sublineView.backgroundColor = kLightGrayColor;
//                [_sideView addSubview:sublineView];
//                if (i == 4) {
//                    sublineView.hidden = YES;
//                }
            }
            
        }
        _sideView.hidden = NO;
    }
    else{
        _sideView.hidden = YES;
    }
    if (_lastIndex != -1) {
        self.filterVC = self.filterVCArray[_lastIndex];
        if ([self.filterVC.view superview]) {
            [self.filterVC dismiss];
        }
        [self.menu setBtnStateWithIndex:_lastIndex state:NO];
        [self.menu setBtnTitleColorWithIndex:_lastIndex state:NO];
    }
    if (!_selectTimeView.hidden) {
        _selectTimeView.hidden = YES;
    }
    if ([self.areaFilterVC.view superview]) {
        [self.areaFilterVC dismiss];
    }
}

- (void)sideButtonAction:(GXButton*)btn{
    if (btn.tag == 10) {
        MSReleaseTradeViewController *vc = [[MSReleaseTradeViewController alloc] init];
        [rootNavigation pushViewController:vc animated:YES];
    }
    else if (btn.tag == 11) {
        MSCustomerMatchingVC *vc = [[MSCustomerMatchingVC alloc] init];
        [rootNavigation pushViewController:vc animated:YES];
    }
    else if (btn.tag == 12) {
        MSCustomerRecommenVC *vc = [[MSCustomerRecommenVC alloc] init];
        [rootNavigation pushViewController:vc animated:YES];
    }
    else if (btn.tag == 13) {
        MSMemberServeViewController *vc = [[MSMemberServeViewController alloc] init];
        vc.memberType = MemberType_advanced;
        [rootNavigation pushViewController:vc animated:YES];
    }
    else if (btn.tag == 14) {
        MSPreferenceSetViewController *vc = [[MSPreferenceSetViewController alloc] init];
        [rootNavigation pushViewController:vc animated:YES];
    }
    _sideView.hidden = YES;
    rightBarBtn.selected = NO;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [netEngine requestMinePageWithTarget:self.VctrID hudView:nil];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if ([self.filterVC.view superview]) {
        [self.filterVC dismiss];
    }
    if (!_selectTimeView.hidden) {//存在选择时间控件
        _selectTimeView.hidden = YES;
    }
    if ([self.areaFilterVC.view superview]) {
        [self.areaFilterVC dismiss];
    }
    _sideView.hidden = YES;
    rightBarBtn.selected = NO;
    [self.menu setBtnStateWithIndex:_lastIndex state:NO];
}

- (NSMutableArray *)creatStateArrayWithArray:(NSArray*)array{
    NSMutableArray *mutalArray = [[NSMutableArray alloc] initWithCapacity:0];
    for (int i= 0; i<array.count; i++) {
        [mutalArray addObject:@"NO"];
    }
    return mutalArray;
}

- (void)layoutHeadView{
    _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100)];
    _headerView.backgroundColor = [UIColor whiteColor];
    self.tableVC.tableView.tableHeaderView = _headerView;
    
    NSMutableAttributedString *tracAttstr = [[NSMutableAttributedString alloc] initWithString:@"我跟踪的\n" attributes:@{NSForegroundColorAttributeName:kDarkGrayColor}];
    NSAttributedString *tracStr = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"0"] attributes:@{NSForegroundColorAttributeName:kLightBlackColor}];
    [tracAttstr appendAttributedString:tracStr];

    self.trackBtn = [self creatBtnWithFrame:CGRectMake(0, 0, BtnWidth, 50) andImage:@"" andTitle:@""];//track
//    [self.trackBtn setAttributedTitle:tracAttstr forState:UIControlStateNormal];
    [self.trackBtn setTitle:@"我跟踪的 0  》" forState:UIControlStateNormal];
    
    NSMutableAttributedString *attentionAttstr = [[NSMutableAttributedString alloc] initWithString:@"我关注的\n" attributes:@{NSForegroundColorAttributeName:kDarkGrayColor}];
    NSAttributedString *attentionStr = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"0"]  attributes:@{NSForegroundColorAttributeName:kLightBlackColor}];
    [attentionAttstr appendAttributedString:attentionStr];
    
    self.attentionBtn = [self creatBtnWithFrame:CGRectMake(BtnWidth, 0, BtnWidth, 50) andImage:@"" andTitle:@""];//guanzhu
//    [self.attentionBtn setAttributedTitle:attentionAttstr forState:UIControlStateNormal];
    [self.attentionBtn setTitle:@"我关注的 0  》" forState:UIControlStateNormal];
    
//    self.recommendBtn = [self creatBtnWithFrame:CGRectMake(BtnWidth*2, 0, BtnWidth, 70) andImage:@"yinjian" andTitle:@"找人脉"];
//    [self.recommendBtn setTitleColor:kLightBlackColor forState:UIControlStateNormal];
//    self.recommendBtn.tag = 30;

    self.trackBtn.tag = 10;
    self.attentionBtn.tag = 20;
    
    for (int i=1; i<2; i++) {
        UIView *horizonLineView =[[UIView alloc] initWithFrame:CGRectMake(i*SCREEN_WIDTH/2, 0, 0.5, 70)];
        horizonLineView.backgroundColor = kNormalGray;
        [_headerView addSubview:horizonLineView];
    }
    UIView *straightLineView =[[UIView alloc] initWithFrame:CGRectMake(0, _trackBtn.bottom-0.6, SCREEN_WIDTH, 0.6)];
    straightLineView.backgroundColor = kNormalGray;
    [_headerView addSubview:straightLineView];
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, _trackBtn.bottom, SCREENFRAME.size.width, 50)];
    bgView.backgroundColor = kDefaultViewBackgroundColor;
    [_headerView addSubview:bgView];
    
    GXButton *setBtn1 = [self creatBtnWithFrame:CGRectMake(12, _trackBtn.bottom+10, SCREEN_WIDTH-52, 30) andImage:@"" andTitle:@"我的订阅"];
    setBtn1.relayout = YES;
    setBtn1.titleLabelFrame = CGRectMake(10, 0, 100, 30);
    setBtn1.layer.borderColor = kNormalGray.CGColor;
    setBtn1.layer.borderWidth = 0.6;
    setBtn1.layer.cornerRadius = 2;
    setBtn1.backgroundColor = [UIColor whiteColor];
    setBtn1.titleLabel.textAlignment = NSTextAlignmentLeft;
    setBtn1.tag = 50;
    
    GXButton *setBtn = [self creatBtnWithFrame:CGRectMake(SCREEN_WIDTH-40, _trackBtn.bottom+5, 40, 40) andImage:@"pianhao" andTitle:@""];
    setBtn.relayout = NO;
    setBtn.tag = 50;
    
//    NSArray *titleArr = [NSArray arrayWithObjects:@"地区",@"行业",@"阶段",@"投资",@"时间", nil];
//    self.menu = [[HDImageMenuView alloc] initWithFrame:CGRectMake(0, 120, SCREEN_WIDTH, 40) titleArray:titleArr];
//    self.menu.delegate = (id)self;
//    self.menu.isHiddenBottomLine = NO;
//    [_headerView addSubview:self.menu];
}

- (void)setHeadTitleWithUserModel:(MSUserInfoModel*)userModel{
    NSMutableAttributedString *tracAttstr = [[NSMutableAttributedString alloc] initWithString:@"我跟踪的\n" attributes:@{NSForegroundColorAttributeName:kDarkGrayColor}];
    NSAttributedString *tracStr = [[NSAttributedString alloc] initWithString:userModel.tracNum attributes:@{NSForegroundColorAttributeName:kLightBlackColor}];
    [tracAttstr appendAttributedString:tracStr];
//    [self.trackBtn setAttributedTitle:tracAttstr forState:UIControlStateNormal];
    [self.trackBtn setTitle:[NSString stringWithFormat:@"我跟踪的 %@  》",userModel.tracNum] forState:UIControlStateNormal];
    
    NSMutableAttributedString *attentionAttstr = [[NSMutableAttributedString alloc] initWithString:@"我关注的\n" attributes:@{NSForegroundColorAttributeName:kDarkGrayColor}];
    NSAttributedString *attentionStr = [[NSAttributedString alloc] initWithString:userModel.atentionNum  attributes:@{NSForegroundColorAttributeName:kLightBlackColor}];
    [attentionAttstr appendAttributedString:attentionStr];
//    [self.attentionBtn setAttributedTitle:attentionAttstr forState:UIControlStateNormal];
    [self.attentionBtn setTitle:[NSString stringWithFormat:@"我关注的 %@  》",userModel.atentionNum] forState:UIControlStateNormal];
}

//创建btn
- (GXButton*)creatBtnWithFrame:(CGRect)frame andImage:(NSString*)imageStr  andTitle:(NSString*)title{
    GXButton *btn = [GXButton buttonWithType:UIButtonTypeCustom];
//    btn.relayout = YES;
    btn.frame = frame;
//    btn.imageViewFrame = CGRectMake((BtnWidth-95)/2, 15, 40, 40);
//    btn.titleLabelFrame = CGRectMake((BtnWidth-95)/2+40, 0, 60, 70);
    btn.titleLabel.numberOfLines = 0;
//    [btn.titleLabel setBackgroundColor:kDarkGrayColor];
    btn.titleLabel.textAlignment = NSTextAlignmentCenter;
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:kLightBlackColor forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont fontWithName:@"STHeitiSC-Light" size:13];
    [btn setImage:[UIImage imageNamed:imageStr] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(headBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_headerView addSubview:btn];
    return btn;
}

- (NSMutableAttributedString *)setTitleWithTitle:(NSString*)title andValue:(NSString*)value{
    NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:title];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 1;
    [attriStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0,title.length+value.length)];
    
    NSAttributedString *titleStr = [[NSAttributedString alloc] initWithString:@"" attributes:@{NSFontAttributeName:HeitiFont(13),NSForegroundColorAttributeName:kDarkGrayColor}];
    [attriStr appendAttributedString:titleStr];
    
    return attriStr;
}

- (void)initPreference{
    //区域
    NSString *areaCodeFile = [documentsPath stringByAppendingPathComponent:@"areaCodeFile.plist"];
    if ([fileManager fileExistsAtPath:areaCodeFile]) {
        NSMutableArray *areaCodeArray = [[NSMutableArray alloc] initWithContentsOfFile:areaCodeFile];
        _areaStr = [areaCodeArray componentsJoinedByString:@","];
        currentProviceStr = _areaStr;
        //        isSelectArea = NO;
    }
    else{
        _areaStr = @"";
    }
    //行业
    NSString *industryCodeFile = [documentsPath stringByAppendingPathComponent:@"industryCodeFile.plist"];
    if ([fileManager fileExistsAtPath:industryCodeFile]) {
        NSMutableArray *industryCodeArray = [[NSMutableArray alloc] initWithContentsOfFile:industryCodeFile];
        _industryStr = [industryCodeArray componentsJoinedByString:@","];
        currentIndustryStr = _industryStr;
        //        isSelectIndustry = NO;
    }
    else{
        _industryStr = @"";
    }
    //阶段
    NSString *stageCodeFile = [documentsPath stringByAppendingPathComponent:@"stageCodeFile.plist"];
    if ([fileManager fileExistsAtPath:stageCodeFile]) {
        NSMutableArray *stageCodeArray = [[NSMutableArray alloc] initWithContentsOfFile:stageCodeFile];
        _stateStr = [stageCodeArray componentsJoinedByString:@","];
        currentStateStr = _stateStr;
        //        isSelectStage = NO;
    }
    else{
        _stateStr = @"";
    }
    self.tableVC.pageNum = 1;
    [self request:NO];
}

#pragma mark - 接收偏好设置修改通知
- (void)preferenceAreaChange{
    //区域
    NSString *areaCodeFile = [documentsPath stringByAppendingPathComponent:@"areaCodeFile.plist"];
    if ([fileManager fileExistsAtPath:areaCodeFile]) {
        NSMutableArray *areaCodeArray = [[NSMutableArray alloc] initWithContentsOfFile:areaCodeFile];
        _areaStr = [areaCodeArray componentsJoinedByString:@","];
        currentProviceStr = _areaStr;
//        isSelectArea = NO;
    }
    else{
        _areaStr = @"";
    }
    if (!isSelectArea) {
        self.tableVC.pageNum = 1;
        [self request:NO];
    }
}

- (void)preferenceIndustryChange{
    //行业
    NSString *industryCodeFile = [documentsPath stringByAppendingPathComponent:@"industryCodeFile.plist"];
    if ([fileManager fileExistsAtPath:industryCodeFile]) {
        NSMutableArray *industryCodeArray = [[NSMutableArray alloc] initWithContentsOfFile:industryCodeFile];
        _industryStr = [industryCodeArray componentsJoinedByString:@","];
        currentIndustryStr = _industryStr;
//        isSelectIndustry = NO;
    }
    else{
        _industryStr = @"";
    }
    if (!isSelectIndustry) {
        self.tableVC.pageNum = 1;
        [self request:NO];
    }
}

- (void)preferenceStageChange{
    //阶段
    NSString *stageCodeFile = [documentsPath stringByAppendingPathComponent:@"stageCodeFile.plist"];
    if ([fileManager fileExistsAtPath:stageCodeFile]) {
        NSMutableArray *stageCodeArray = [[NSMutableArray alloc] initWithContentsOfFile:stageCodeFile];
        _stateStr = [stageCodeArray componentsJoinedByString:@","];
        currentStateStr = _stateStr;
//        isSelectStage = NO;
    }
    else{
        _stateStr = @"";
    }
    if (!isSelectStage) {
        self.tableVC.pageNum = 1;
        [self request:NO];
    }
}

- (void)loginSuccess{
    self.tableVC.pageNum = 1;
    [self request:NO];
}

- (void)testDataFunc{
    self.stateVCArray = [NSMutableArray arrayWithObjects:@"",@"",@"",@"",@"", nil];
    
    fileManager = [NSFileManager defaultManager];
    documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) firstObject];
    
    BOOL hasCity = NO;
    //省市
    NSString *tradeTypeFile = [documentsPath stringByAppendingPathComponent:@"provincesFile.plist"];
    if ([fileManager fileExistsAtPath:tradeTypeFile]) {
        hasCity = YES;
    }
    else {
        //省市、行业、时间
        [netEngine requestTradeScreeningConditionsWithTarget:self.VctrID hudView:nil];
    }
    
    BOOL hasState = NO;
    //阶段
    NSString *projectStateFile = [documentsPath stringByAppendingPathComponent:@"projectStateFile.plist"];
    if ([fileManager fileExistsAtPath:projectStateFile]) {
        hasState = YES;
    }
    else{
        [netEngine requestProjectStateWithTarget:self.VctrID hudView:nil];
    }
    
    BOOL hasInvestment = NO;
    
    //投资
    NSString *projectInvestmentFile = [documentsPath stringByAppendingPathComponent:@"projectInvestmentFile.plist"];
    if ([fileManager fileExistsAtPath:projectInvestmentFile]) {
        hasInvestment = YES;
    }
    else{
        [netEngine requestProjectInvestmentWithTarget:self.VctrID hudView:nil];
    }
    
    if (hasCity && hasState && hasInvestment) {
        [self fillFilterData];
    }
    /*
    MSProjectModel *model = [[MSProjectModel alloc] init];
    model.title = @"上海浦东世和空港中心商业住房项目";
    model.projectType =  @"房地产";
    model.projectState =  @"主体施工";
    model.investment =  @"2亿";
    model.address =  @"上海";
    model.time =  @"2016.10.08";
    model.introduction =  @"项目为四栋单独塔楼，一座宾馆，一做酒店式办公楼，整个项目投资回报率较高";
    
    MSProjectModel *model1 = [[MSProjectModel alloc] init];
    model1.title = @"苏州永华置业有限公司 意境鸣镝西部仓库";
    model1.projectType =  @"酒店";
    model1.projectState =  @"主体施工";
    model1.investment =  @"3亿";
    model1.address =  @"苏州";
    model1.time =  @"2016.10.08";
    model1.introduction =  @"项目为四栋单独塔楼，一座宾馆。";
    
    MSProjectModel *model2 = [[MSProjectModel alloc] init];
    model2.title = @"中国光大国际有限公司深圳办事处";
    model2.projectType =  @"市政公用";
    model2.projectState =  @"主体施工";
    model2.investment =  @"6亿";
    model2.address =  @"成都";
    model2.time =  @"2016.9.15";
    model2.introduction =  @"项目为四栋单独塔楼，一座宾馆，一做酒店式办公楼，地下部分主题为一个小楼盘";
    
    self.tableVC.dataArray = [@[model,model1,model2,model,model2,model1,model] mutableCopy];
    */
}

- (void)fillFilterData{
    //省市、行业、时间
    [self fillProvincesFilterData];

    //阶段
    NSMutableArray *tempDataArray3 = [[NSMutableArray alloc] initWithCapacity:0];
    NSMutableArray *tempCodeArray3 = [[NSMutableArray alloc] initWithCapacity:0];
    NSString *projectStateFile = [documentsPath stringByAppendingPathComponent:@"projectStateFile.plist"];
    if ([fileManager fileExistsAtPath:projectStateFile]) {
        netEngine.projectStateArray = [[NSMutableArray alloc] initWithContentsOfFile:projectStateFile];
    }
    for (NSDictionary *dict in netEngine.projectStateArray) {
        if ([dict isKindOfClass:[NSDictionary class]]) {
            [tempDataArray3 addObject:[HDUtil check:dict[@"name"]]];
            [tempCodeArray3 addObject:[HDUtil check:dict[@"code"]]];
        }
    }
    self.stateFilterVC.dataArray = tempDataArray3;
    self.stateFilterVC.codeArray = tempCodeArray3;
    self.stateFilterVC.stateArray = [self creatStateArrayWithArray:self.stateFilterVC.dataArray];
    [self.stateVCArray replaceObjectAtIndex:2 withObject:self.stateFilterVC.stateArray];

    //投资
    NSMutableArray *tempDataArray4 = [[NSMutableArray alloc] initWithCapacity:0];
    NSMutableArray *tempCodeArray4 = [[NSMutableArray alloc] initWithCapacity:0];
    NSString *projectInvestmentFile = [documentsPath stringByAppendingPathComponent:@"projectInvestmentFile.plist"];
    if ([fileManager fileExistsAtPath:projectInvestmentFile]) {
        netEngine.projectInvestmentArray = [[NSMutableArray alloc] initWithContentsOfFile:projectInvestmentFile];
    }
    for (NSDictionary *dict in netEngine.projectInvestmentArray) {
        if ([dict isKindOfClass:[NSDictionary class]]) {
            [tempDataArray4 addObject:[HDUtil check:dict[@"name"]]];
            [tempCodeArray4 addObject:[HDUtil check:dict[@"code"]]];
        }
    }
    self.investFilterVC.dataArray = tempDataArray4;
    self.investFilterVC.codeArray = tempCodeArray4;
    self.investFilterVC.stateArray = [self creatStateArrayWithArray:self.investFilterVC.dataArray];
    [self.stateVCArray replaceObjectAtIndex:3 withObject:self.investFilterVC.stateArray];
    
    //    self.stateFilterVC.dataArray = [netEngine.projectStateArray mutableCopy];
    //    self.investFilterVC.dataArray = [netEngine.projectInvestmentArray mutableCopy];
    //    self.timeFilterVC.dataArray = [netEngine.projectTimeArray mutableCopy];
    
    //    self.industryFilterVC.dataArray = [@[@"推荐",@"电力", @"能源矿产", @"冶金", @"化工医疗", @"轻纺食品", @"环保", @"市政公用", @"交通运输", @"机械电子", @"建筑", @"建材", @"农林水利", @"生态休闲旅游", @"其他"] mutableCopy];
    //    self.stateFilterVC.dataArray = [@[@"推荐",@"工程筹备", @"勘察设计", @"主体施工", @"设备安装", @"装饰装修", @"园林绿化", @"竣工测试"] mutableCopy];
    //    self.investFilterVC.dataArray = [@[@"不限",@"5000万以下",@"5000万-1亿",@"1亿-5亿",@"3000万-8000万",@"5亿-10亿",@"10亿以上"] mutableCopy];
    //    self.timeFilterVC.dataArray = [@[@"不限",@"最近1个月",@"最近3个月",@"最近半年",@"最近1年",@"自定义"] mutableCopy];
    
//    self.stateVCArray = [NSMutableArray arrayWithObjects:@"",self.industryFilterVC.stateArray,self.stateFilterVC.stateArray,self.investFilterVC.stateArray,self.timeFilterVC.stateArray, nil];
}

- (void)fillProvincesFilterData{
    //省市
    NSMutableArray *tempDataArray = [[NSMutableArray alloc] initWithCapacity:0];
    NSMutableArray *tempCodeArray = [[NSMutableArray alloc] initWithCapacity:0];
    NSString *provincesFile = [documentsPath stringByAppendingPathComponent:@"provincesFile.plist"];
    if ([fileManager fileExistsAtPath:provincesFile]) {
        netEngine.provincesArray = [[NSMutableArray alloc] initWithContentsOfFile:provincesFile];
    }
    for (NSDictionary *dict in netEngine.provincesArray) {
        if ([dict isKindOfClass:[NSDictionary class]]) {
            NSArray *tempArray = [HDUtil checkArray:dict[@"citys"]];
            NSMutableArray *citysArray = [NSMutableArray arrayWithCapacity:0];
            NSMutableArray *citysCodeArray = [NSMutableArray arrayWithCapacity:0];
            for (NSDictionary *provinceDict in tempArray) {
                if ([provinceDict isKindOfClass:[NSDictionary class]]){
                    [citysArray addObject:[HDUtil check:provinceDict[@"name"]]];
                    [citysCodeArray addObject:[HDUtil check:provinceDict[@"code"]]];
                }
            }
            NSDictionary *chinaDict = @{[HDUtil check:dict[@"name"]]:citysArray};
            NSDictionary *chinaCodeDict = @{[HDUtil check:dict[@"code"]]:citysCodeArray};
            [tempDataArray addObject:chinaDict];
            [tempCodeArray addObject:chinaCodeDict];
        }
    }
    self.areaFilterVC.codeArray = tempCodeArray;
    self.areaFilterVC.dataArray = tempDataArray;
    
    //行业
    NSMutableArray *tempDataArray2 = [[NSMutableArray alloc] initWithCapacity:0];
    NSMutableArray *tempCodeArray2 = [[NSMutableArray alloc] initWithCapacity:0];
    
    NSString *projectIndustryFile = [documentsPath stringByAppendingPathComponent:@"projectIndustryFile.plist"];
    if ([fileManager fileExistsAtPath:projectIndustryFile]) {
        netEngine.projectIndustryArray = [[NSMutableArray alloc] initWithContentsOfFile:projectIndustryFile];
    }
    for (NSDictionary *dict in netEngine.projectIndustryArray) {
        if ([dict isKindOfClass:[NSDictionary class]]) {
            [tempDataArray2 addObject:[HDUtil check:dict[@"name"]]];
            [tempCodeArray2 addObject:[HDUtil check:dict[@"code"]]];
        }
    }
    self.industryFilterVC.dataArray = tempDataArray2;
    self.industryFilterVC.codeArray = tempCodeArray2;
    self.industryFilterVC.stateArray = [self creatStateArrayWithArray:self.industryFilterVC.dataArray];
    [self.stateVCArray replaceObjectAtIndex:1 withObject:self.industryFilterVC.stateArray];
    
    //时间
    NSMutableArray *tempDataArray5 = [[NSMutableArray alloc] initWithCapacity:0];
    NSMutableArray *tempCodeArray5 = [[NSMutableArray alloc] initWithCapacity:0];
    NSString *projectTimeFile = [documentsPath stringByAppendingPathComponent:@"projectTimeFile.plist"];
    if ([fileManager fileExistsAtPath:projectTimeFile]) {
        netEngine.projectTimeArray = [[NSMutableArray alloc] initWithContentsOfFile:projectTimeFile];
    }
    for (NSDictionary *dict in netEngine.projectTimeArray) {
        if ([dict isKindOfClass:[NSDictionary class]]) {
            [tempDataArray5 addObject:[HDUtil check:dict[@"name"]]];
            [tempCodeArray5 addObject:[HDUtil check:dict[@"code"]]];
        }
    }
    self.timeFilterVC.dataArray = tempDataArray5;
    self.timeFilterVC.codeArray = tempCodeArray5;
    self.timeFilterVC.stateArray = [self creatStateArrayWithArray:self.timeFilterVC.dataArray];
    [self.stateVCArray replaceObjectAtIndex:4 withObject:self.timeFilterVC.stateArray];
}

#pragma mark - 数据处理
- (void)updateViewController:(NSNotification *)note {
    NSDictionary *responseDic = note.userInfo;
    if (responseDic[Receiver]==self.VctrID) {
        if (responseDic[@"MinePage"]!=nil){
            MSUserInfoModel *userModel = responseDic[@"MinePage"];
            [self setHeadTitleWithUserModel:userModel];
        }
        if (responseDic[@"ProjectList"]!=nil){
            if (responseDic[@"state"]!=nil){
                self.tableVC.totalPagesNum = [responseDic[@"totalPage"] intValue];
                if (self.tableVC.pageNum == 1) {
                    self.tableVC.dataArray = nil;
                }
                NSMutableArray *dataArrray = [[NSMutableArray alloc] initWithArray:self.tableVC.dataArray];
                [dataArrray addObjectsFromArray:responseDic[@"ProjectList"]];
                self.tableVC.dataArray = dataArrray;
            }
            else{
                self.tableVC.dataArray = self.tableVC.dataArray;
            }
        }
        if (responseDic[@"TradeScreeningConditions"]!=nil){
            [self fillProvincesFilterData];
        }
        if (responseDic[@"ProjectState"]!=nil){
            NSMutableArray *tempDataArray3 = [[NSMutableArray alloc] initWithCapacity:0];
            NSMutableArray *tempCodeArray3 = [[NSMutableArray alloc] initWithCapacity:0];
            NSString *projectStateFile = [documentsPath stringByAppendingPathComponent:@"projectStateFile.plist"];
            if ([fileManager fileExistsAtPath:projectStateFile]) {
                netEngine.projectStateArray = [[NSMutableArray alloc] initWithContentsOfFile:projectStateFile];
            }
            for (NSDictionary *dict in netEngine.projectStateArray) {
                if ([dict isKindOfClass:[NSDictionary class]]) {
                    [tempDataArray3 addObject:[HDUtil check:dict[@"name"]]];
                    [tempCodeArray3 addObject:[HDUtil check:dict[@"code"]]];
                }
            }
            self.stateFilterVC.dataArray = tempDataArray3;
            self.stateFilterVC.codeArray = tempCodeArray3;
            self.stateFilterVC.stateArray = [self creatStateArrayWithArray:self.stateFilterVC.dataArray];
            [self.stateVCArray replaceObjectAtIndex:2 withObject:self.stateFilterVC.stateArray];
        }
        if (responseDic[@"ProjectInvestment"]!=nil){
            //投资
            NSMutableArray *tempDataArray4 = [[NSMutableArray alloc] initWithCapacity:0];
            NSMutableArray *tempCodeArray4 = [[NSMutableArray alloc] initWithCapacity:0];
            NSString *projectInvestmentFile = [documentsPath stringByAppendingPathComponent:@"projectInvestmentFile.plist"];
            if ([fileManager fileExistsAtPath:projectInvestmentFile]) {
                netEngine.projectInvestmentArray = [[NSMutableArray alloc] initWithContentsOfFile:projectInvestmentFile];
            }
            for (NSDictionary *dict in netEngine.projectInvestmentArray) {
                if ([dict isKindOfClass:[NSDictionary class]]) {
                    [tempDataArray4 addObject:[HDUtil check:dict[@"name"]]];
                    [tempCodeArray4 addObject:[HDUtil check:dict[@"code"]]];
                }
            }
            self.investFilterVC.dataArray = tempDataArray4;
            self.investFilterVC.codeArray = tempCodeArray4;
            self.investFilterVC.stateArray = [self creatStateArrayWithArray:self.investFilterVC.dataArray];
            [self.stateVCArray replaceObjectAtIndex:3 withObject:self.investFilterVC.stateArray];
        }
    }
}

#pragma mark DYTableViewProtocol
/** 上拉 */
- (void)pullTableView:(UITableView *)tableView isNextPage:(BOOL)isNextPage{
    self.tableVC.pageNum++;
    [self request:YES];
}

- (void)pullRefreshRequest
{
    self.tableVC.pageNum = 1;
    [self request:YES];
}

-(void)request:(BOOL)isPull
{
    UIView * hudView = isPull?nil:self.contentView;
    NSString *pageNumber = [NSString stringWithFormat:@"%d",self.tableVC.pageNum];
    
    NSDictionary *dict = @{@"provinces":currentProviceStr,
                           @"citys":currentCityStr,
                           @"industrys":currentIndustryStr,
                           @"stages":currentStateStr,
                           @"investment":currentInvetStr,
                           @"onlineTime":currentTimeStr,
                           @"kw":@"",
                           @"pageNo":pageNumber,
                           @"pageSize":@"10",
                           };
    NSLog(@"列表参数:%@",dict);
    [netEngine requestProjectListWithTarget:self.VctrID hudView:hudView params:dict];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    MSProjectModel *model = self.tableVC.dataArray[indexPath.row];
    MSProjectDetailViewController *vc = [[MSProjectDetailViewController alloc] init];
    vc.projectId = model.itemID;
    [rootNavigation pushViewController:vc animated:YES];
}

- (void)headBtnClick:(GXButton *)btn{
    if (btn.tag == 10) {
        MSMyFollowViewController *vc = [[MSMyFollowViewController alloc] init];
        [rootNavigation pushViewController:vc animated:YES];
    }
    if (btn.tag == 20) {
        MSMyAttentionViewController *vc = [[MSMyAttentionViewController alloc] init];
        [rootNavigation pushViewController:vc animated:YES];
    }
    if (btn.tag == 30) {
//        [self.menu setBtnStateWithIndex:1 state:YES];
        MSCustomerRecommenVC *vc = [[MSCustomerRecommenVC alloc] init];
        [rootNavigation pushViewController:vc animated:YES];
    }
    if (btn.tag == 40) {//搜索
        MSSearchViewController *vc = [[MSSearchViewController alloc] init];
        vc.searchType = MSSearchType_Project;
        [rootNavigation pushViewController:vc animated:NO];
    }
    if (btn.tag == 50) {
        MSPreferenceSetViewController *vc = [[MSPreferenceSetViewController alloc] init];
        [rootNavigation pushViewController:vc animated:YES];
    }
}

- (void)selectedDate:(NSDate*)startDate end:(NSDate*)endDate{
    _selectTimeView.hidden = YES;
    _selectTime = YES;
    [self.menu setBtnStateWithIndex:_lastIndex state:NO];
    [self.menu setBtnTitleColorWithIndex:4 state:YES];
    [self.filterVC selectedTime];
}

#pragma mark - MSDoubleListFilterVCDelegate
- (void)selectedAreaProviceCode:(NSDictionary *)proviceDict cityCode:(NSDictionary *)cityDict isTap:(BOOL)isTap{//地区
    [self.menu setBtnStateWithIndex:_lastIndex state:NO];
    if (isTap) {
//        [self.menu setBtnStateWithIndex:0 state:NO];
        return;
    }
    NSString *cityName = [cityDict allKeys][0];
    if (cityName.length) {
        isSelectArea = YES;
        currentProviceStr = [proviceDict allValues][0];
        currentCityStr = [cityDict allValues][0];
        [self.menu setBtnTitleColorWithIndex:0 state:YES];
    }
    else{
        isSelectArea = NO;
        currentProviceStr = _areaStr;
        currentCityStr = @"";
        [self.menu setBtnTitleColorWithIndex:0 state:NO];
    }
    self.tableVC.pageNum = 1;
    [self request:NO];
}

#pragma mark - MSSaleFilterDelegate
- (void)selectedFilterWithParmas:(NSInteger)index code:(NSString*)codeValue{// 选择了某一项
    if (_lastIndex == 4) {//时间
        if (index == 100 && !_selectTime) {//自定义时间
            _selectTimeView.hidden = NO;
            _selectTimeView.frame = CGRectMake(0, _positionY+KNavBarHeight, SCREEN_WIDTH, SCREEN_HEIGHT-_positionY - KNavBarHeight);
            [_selectTimeView showInView:SCREEN_HEIGHT-_positionY - KNavBarHeight];
            UIWindow *window = [UIApplication sharedApplication].windows[0];
            [window bringSubviewToFront:_selectTimeView];
            return;
        }
        else{
            [self.menu setBtnTitleColorWithIndex:4 state:YES];
        }
    }
    _selectTime = NO;
    [self.menu setBtnStateWithIndex:_lastIndex state:NO];
    NSArray *stateArray = self.stateVCArray[_lastIndex];
    if ([stateArray containsObject:@"YES"]) {
        [self.menu setBtnTitleColorWithIndex:_lastIndex state:YES];
    }
    else{
        [self.menu setBtnTitleColorWithIndex:_lastIndex state:NO];
    }
    if (_lastIndex == 1) {//行业
        if ([stateArray containsObject:@"YES"]) {
            isSelectIndustry = YES;
            currentIndustryStr = codeValue;
        }
        else{
            isSelectIndustry = NO;
            currentIndustryStr = _industryStr;
        }
    }
    if (_lastIndex == 2) {//阶段
        if ([stateArray containsObject:@"YES"]) {
            isSelectStage = YES;
            currentStateStr = codeValue;
        }
        else{
            isSelectStage = NO;
            currentStateStr = _stateStr;
        }
    }
    if (_lastIndex == 3) {//投资
        if ([stateArray containsObject:@"YES"]) {
            currentInvetStr = codeValue;
        }
        else{
            currentInvetStr = @"";
        }
    }
    if (_lastIndex == 4) {//时间
        if ([stateArray containsObject:@"YES"]) {
            currentTimeStr = codeValue;
        }
        else{
            currentTimeStr = @"";
        }
    }
    if (index != 1000) {
        self.tableVC.pageNum = 1;
        [self request:NO];
    }
}

- (void)selectImageMenuIndex:(int)index{
    if (!_sideView.hidden) {
        _sideView.hidden = YES;
        rightBarBtn.selected = NO;
    }
    if (!_selectTimeView.hidden) {//存在选择时间控件
        _selectTimeView.hidden = YES;
    }
    if (_lastIndex != -1) {//不是第一次
        [self.menu setBtnStateWithIndex:_lastIndex state:NO];
        if (index != 0) {//点击其它
            if (index != _lastIndex) {
                self.filterVC = self.filterVCArray[_lastIndex];
                if ([self.filterVC.view superview]) {
                    [self.filterVC dismiss];
                }
                self.filterVC = self.filterVCArray[index];
                if ([self.filterVC.view superview]) {
                    [self.filterVC dismiss];
                }
                else{
                    [self.filterVC showInView:_positionY];
                    [self.menu setBtnStateWithIndex:index state:YES];
                }
            }
            else{
                self.filterVC = self.filterVCArray[index];
                if ([self.filterVC.view superview]) {
                    [self.filterVC dismiss];
                }
                else{
                    [self.filterVC showInView:_positionY];
                    [self.menu setBtnStateWithIndex:index state:YES];
                }
            }
        }
        else{//点击地区
            if (_lastIndex != 0) {
                self.filterVC = self.filterVCArray[_lastIndex];
                if ([self.filterVC.view superview]) {
                    [self.filterVC dismiss];
                }
            }
            
            if ([self.areaFilterVC.view superview]) {
                [self.areaFilterVC dismiss];
                [self.menu setBtnStateWithIndex:index state:NO];
            } else {
                [self.areaFilterVC showInView:_positionY];
                [self.menu setBtnStateWithIndex:index state:YES];
            }
        }
    }
    else{//第一次点击
        if (index != 0) {//1
            if ([self.areaFilterVC.view superview]) {
                [self.areaFilterVC dismiss];
            } else {
                if (_lastIndex != -1 && _lastIndex != 0) {
                    self.filterVC = self.filterVCArray[_lastIndex];
                    if ([self.filterVC.view superview]) {
                        [self.filterVC dismiss];
                    } else {//旧的不在
                        self.filterVC = self.filterVCArray[index];
                        if ([self.filterVC.view superview]) {
                            [self.filterVC dismiss];
                        }
                        else{
                            [self.filterVC showInView:_positionY];
                            [self.menu setBtnStateWithIndex:index state:YES];
                        }
                    }
                }
                else{//第一次点击
                    self.filterVC = self.filterVCArray[index];
                    
                    if ([self.filterVC.view superview]) {
                        [self.filterVC dismiss];
                    }
                    else{
                        [self.filterVC showInView:_positionY];
                        [self.menu setBtnStateWithIndex:index state:YES];
                    }
                }
            }
        }
        else{//点击地区
            if ([self.areaFilterVC.view superview]) {
                [self.areaFilterVC dismiss];
                [self.menu setBtnStateWithIndex:index state:NO];
            } else {
                [self.areaFilterVC showInView:_positionY];
                [self.menu setBtnStateWithIndex:index state:YES];
            }
        }
    }
    _lastIndex = index;
}

- (MSSaleFilterViewController *)creatFilterVC
{
    MSSaleFilterViewController *VC = [[MSSaleFilterViewController alloc] init];
    VC.delegate = (id<MSSaleFilterDelegate>)self;
    return VC;
}

- (MSDoubleListFilterVC *)areaFilterVC
{
    if (!_areaFilterVC) {
        _areaFilterVC = [[MSDoubleListFilterVC alloc] init];
        _areaFilterVC.delegate=(id<MSDoubleListFilterVCDelegate>)self;
    }
    return _areaFilterVC;
}

#pragma mark - scrollviewBeginDragging
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if ([self.filterVC.view superview]) {
        [self.filterVC dismiss];
    }
    if (!_selectTimeView.hidden) {//存在选择时间控件
        _selectTimeView.hidden = YES;
    }
    if ([self.areaFilterVC.view superview]) {
        [self.areaFilterVC dismiss];
    }
    _sideView.hidden = YES;
    rightBarBtn.selected = NO;
    [self.menu setBtnStateWithIndex:_lastIndex state:NO];
}

@end
